/**
 * 候选人更多操作弹框
 */
import React from 'react';
import { Modal, Form, Input, Radio, Select, Checkbox, Row, Alert, Spin, message } from 'antd';
import { useRequest, defaultFormatResult } from '@/hooks';
import { getEmployeeInfoList } from '@/services/components/userform';
import helper from '@/utils/auth/helper';
import {
    queryRecommendPositionList,
    operateForResume,
    getProcessStatusByResumeId,
    queryRecommendCodePositionList
} from '../../service';
import { CANDIDATE_OPERATE_TYPE } from '../../dictionary';

const { checkCode } = helper;

const FORM_DEFAULT_LAYOUT = {
    labelCol: {
        span: 5
    },
    wrapperCol: {
        span: 17
    }
};
const { TextArea } = Input;
const { Option } = Select;
const MoreOperateModal = ({
    form,
    resumeId,
    onOk,
    visible,
    destroyOnClose = true,
    recommendOutDisabled = false,
    operate,
    talentCode,
    showSelect = true,
    ...rest
}) => {
    const noticeFlag = checkCode('office:recruitment:course:notice');
    // const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
    // const { companyId } = user;
    const { getFieldDecorator, validateFields, getFieldValue, resetFields } = form;
    const currOperateType = React.useMemo(() => {
        if (!getFieldValue('operateType')) {
            return operate?.[0];
        }
        return getFieldValue('operateType');
    }, [getFieldValue('operateType'), operate]);

    // 必须添加的通知人员，且不允许删除
    const [mustNotice, setMustNotice] = React.useState([]);
    // 岗位列表
    const { data: postList } = useRequest(
        () => {
            if (visible && talentCode) return queryRecommendCodePositionList(talentCode);
            if (visible && resumeId) return queryRecommendPositionList(resumeId);
            return Promise.resolve({ code: 10000, data: [] });
        },
        {
            initialData: [],
            refreshDeps: [resumeId, visible],
            ...defaultFormatResult
        }
    );
    // hintType
    const { data: processStatus, loading: processLoading } = useRequest(
        () => {
            if (visible && resumeId) return getProcessStatusByResumeId(resumeId);
            return Promise.resolve({ code: 10000, data: {} });
        },
        {
            initialData: {},
            refreshDeps: [resumeId, visible],
            ...defaultFormatResult
        }
    );
    // 获取人员
    const { data: employeeList, loading: employeeLoading } = useRequest(
        () => {
            if (visible) {
                return getEmployeeInfoList({
                    // administrativeOrganizationCode: companyId
                });
            }
            return Promise.resolve({ code: 10000, data: [] });
        },
        {
            refreshDeps: [visible],
            initialData: [],
            ...defaultFormatResult
        }
    );
    const currRecommendRecruitId = form.getFieldValue('recommendRecruitId');
    // 通知人员赋值
    React.useEffect(() => {
        setMustNotice([]);
        if (!currRecommendRecruitId || !postList || !postList.length) {
            return;
        }
        const target = postList.find(item => item.recruitId === currRecommendRecruitId);
        if (!target) {
            return;
        }
        const { launchEmployeeCode, principalEmployeeCode } = target;
        const set = new Set(
            principalEmployeeCode !== '' ? [launchEmployeeCode, principalEmployeeCode] : [launchEmployeeCode]
        );
        setMustNotice([...set]);
        form.setFieldsValue({
            noticeEmployeeCodeList: [...set]
        });
    }, [currRecommendRecruitId, postList]);
    const [submitLoading, setSubmitLoading] = React.useState(false);
    const handleOk = () => {
        validateFields((err, values) => {
            if (err) {
                return;
            }
            const trans = val => (val ? 1 : 0);
            const { currentPositionEliminateFlag, operateType, emailNotifyFlag } = values;
            let p = values;
            if (operateType === 1) {
                p = {
                    ...values,
                    emailNotifyFlag: trans(emailNotifyFlag)
                };
            } else if ([2, 5].includes(operateType)) {
                p = {
                    ...values,
                    operateType,
                    currentPositionEliminateFlag: trans(currentPositionEliminateFlag)
                };
            }
            setSubmitLoading(true);
            // 通知候选人 /office/personnelManagement/recruitment/candidate/notice
            operateForResume(resumeId, p).then(res => {
                const { code, msg } = res;
                setSubmitLoading(false);
                if (code === 10000) {
                    if (onOk) {
                        onOk({
                            emailNoticeFlag: emailNotifyFlag,
                            refreshFlag: operateType === 1 || operateType === 5 || currentPositionEliminateFlag
                        });
                    }
                    if ([2, 5].includes(operateType)) {
                        message.success('成功推荐到其他部门');
                    }
                } else {
                    message.error(msg);
                    console.error('操作失败~~~');
                }
            });
        });
    };
    // 为了卸载
    const [alertHidden, setAlertHidden] = React.useState(false);
    const [warnFlag, setWarnFlag] = React.useState(false);
    React.useEffect(() => {
        setWarnFlag(
            processStatus?.hintType === 1 && (currOperateType === 1 || getFieldValue('currentPositionEliminateFlag'))
        );
    }, [processStatus?.hintType, currOperateType, getFieldValue('currentPositionEliminateFlag')]);
    return (
        <Modal
            {...rest}
            visible={visible}
            width={720}
            onOk={handleOk}
            confirmLoading={submitLoading}
            destroyOnClose={destroyOnClose}
            afterClose={() => {
                resetFields();
                setAlertHidden(false);
            }}
        >
            <Spin spinning={processLoading || employeeLoading}>
                <div style={{ margin: '0 48px' }}>
                    {warnFlag && !alertHidden && (
                        <Alert
                            message="该候选人有未完成的面试安排，如果淘汰将自动取消"
                            type="warning"
                            showIcon
                            closable
                            afterClose={() => setAlertHidden(true)}
                        />
                    )}
                </div>
                <Form {...FORM_DEFAULT_LAYOUT}>
                    <div style={{ display: showSelect ? '' : 'none' }}>
                        <Form.Item label="选择操作">
                            {getFieldDecorator('operateType', {
                                initialValue: operate?.[0] || 1
                            })(
                                <Radio.Group>
                                    {CANDIDATE_OPERATE_TYPE.filter(
                                        item => operate.findIndex(opItem => item.value === opItem) !== -1
                                    ).map(item => (
                                        <Radio value={item.value} key={item.value}>
                                            {item.text}
                                        </Radio>
                                    ))}
                                </Radio.Group>
                            )}
                        </Form.Item>
                    </div>
                    {[2, 5].includes(currOperateType) && (
                        <>
                            <Form.Item label="推荐岗位">
                                <Row type="flex">
                                    <div>
                                        {getFieldDecorator('recommendRecruitId', {
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '推荐岗位不能为空'
                                                },
                                                {
                                                    validator: (rule, value, callback) => {
                                                        if (!value || !postList?.length) {
                                                            return callback();
                                                        }
                                                        const flag = postList.find(item => item?.recruitId === value)
                                                            ?.existState;
                                                        if (flag) {
                                                            return callback('当前候选人已应聘此招聘岗位，请勿重复推荐');
                                                        }
                                                        return callback();
                                                    }
                                                }
                                            ]
                                        })(
                                            <Select
                                                showSearch
                                                style={{ width: 285 }}
                                                placeholder="请选择推荐岗位 - 部门（招聘负责人）"
                                                optionFilterProp="children"
                                                dropdownMatchSelectWidth={false}
                                                dropdownStyle={{ maxWidth: 550 }}
                                                getPopupContainer={triggerNode => triggerNode.parentElement}
                                            >
                                                {postList?.map(item => (
                                                    <Option value={item.recruitId} key={item.recruitId}>
                                                        {`${item.name}（${item.principalEmployeeName || '--'}）`}
                                                    </Option>
                                                ))}
                                            </Select>
                                        )}
                                    </div>
                                    {currOperateType === 2 && (
                                        <Form.Item style={{ marginBottom: 0 }}>
                                            <div style={{ height: 40, marginLeft: 10 }}>
                                                {getFieldDecorator('currentPositionEliminateFlag', {
                                                    initialValue: !recommendOutDisabled,
                                                    valuePropName: 'checked'
                                                })(
                                                    <Checkbox
                                                        disabled={recommendOutDisabled}
                                                        style={{
                                                            visibility: recommendOutDisabled ? 'hidden' : 'visible'
                                                        }}
                                                    >
                                                        从当前应聘岗位中淘汰
                                                    </Checkbox>
                                                )}
                                            </div>
                                        </Form.Item>
                                    )}
                                </Row>
                            </Form.Item>

                            <Form.Item label="通知人员">
                                {getFieldDecorator(
                                    'noticeEmployeeCodeList',
                                    {}
                                )(
                                    <Select
                                        mode="multiple"
                                        style={{ width: '100%' }}
                                        placeholder="请选择通知人员"
                                        allowClear
                                        optionFilterProp="children"
                                        getPopupContainer={triggerNode => triggerNode.parentElement}
                                    >
                                        {employeeList?.map(item => (
                                            <Option
                                                value={item.employeeCode}
                                                key={item.employeeCode}
                                                disabled={mustNotice.includes(item.employeeCode)}
                                            >
                                                {item.employeeName}
                                            </Option>
                                        ))}
                                    </Select>
                                )}
                            </Form.Item>
                        </>
                    )}
                    {currOperateType === 3 && (
                        <Form.Item label="接收人">
                            {getFieldDecorator('receiveEmployeeCodeList', {
                                rules: [
                                    {
                                        required: true,
                                        message: '接收人不能为空'
                                    }
                                ]
                            })(
                                <Select
                                    mode="multiple"
                                    style={{ width: '100%' }}
                                    placeholder="请选择接收人"
                                    optionFilterProp="children"
                                    allowClear
                                    getPopupContainer={triggerNode => triggerNode.parentElement}
                                >
                                    {employeeList?.map(item => (
                                        <Option value={item.employeeCode} key={item.employeeCode}>
                                            {item.employeeName}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Form.Item>
                    )}
                    {[1, 2, 5].includes(currOperateType) && (
                        <Form.Item label="理由">
                            {getFieldDecorator('reason', {
                                initialValue: '',
                                rules: [
                                    {
                                        required: true,
                                        message: '理由不能为空'
                                    }
                                ]
                            })(
                                <TextArea
                                    placeholder="请输入理由"
                                    autoSize={{ minRows: 3, maxRows: 6 }}
                                    maxLength={800}
                                />
                            )}
                        </Form.Item>
                    )}
                    {currOperateType === 3 && (
                        <Form.Item label="备注">
                            {getFieldDecorator('remark', {
                                initialValue: ''
                            })(
                                <TextArea
                                    placeholder="请输入备注"
                                    autoSize={{ minRows: 3, maxRows: 6 }}
                                    maxLength={800}
                                />
                            )}
                        </Form.Item>
                    )}
                    {currOperateType === 1 && noticeFlag && (
                        <Form.Item label="邮件通知候选人">
                            {getFieldDecorator('emailNotifyFlag', {
                                initialValue: 1
                            })(
                                <Radio.Group>
                                    <Radio value={1}>是</Radio>
                                    <Radio value={0}>否</Radio>
                                </Radio.Group>
                            )}
                            {getFieldValue('emailNotifyFlag') === 1 && (
                                <div style={{ color: 'rgba(0,0,0,0.65)', fontSize: 12 }}>
                                    点击确定后，将打开通知候选人页面
                                </div>
                            )}
                        </Form.Item>
                    )}
                </Form>
            </Spin>
        </Modal>
    );
};

export default Form.create()(MoreOperateModal);
